import React, { useState, useEffect } from 'react';
import {Card, Table, Button, Space, Select, message, Row, Col, Tabs} from 'antd';
import ReactECharts from 'echarts-for-react';

import styles from './index.module.css';
import {textApi, TextDataResponseVO} from "../../../services/api/text";
import {algorithmApi, AlgorithmConfigVO} from '../../../services/api/algorithm';
const { TabPane } = Tabs;
// 定义请求参数接口
interface SimilarityRequest {
    textId1: number;
    textId2: number;
    algorithmId: number;
}

// 定义返回结果接口
interface SimilarityResult {
    resultId: number | null;
    textId1: number | null;
    textId2: number | null;
    algorithmId: number | null;
    score: number;
    comparisonType: string | null;
    createdAt: string | null;
    chartData: {
        similarityGauge: {
            score: number;
            thresholds: {
                high: number;
                low: number;
                medium: number;
            };
        };
        wordFrequency: {
            text1Frequencies: number[];
            text2Frequencies: number[];
            labels: string[];
        };
    };
    similarSegments: string;
    differentSegments: string;
    analysisDetails: {
        text1Length: number;
        text2Length: number;
        commonTermsCount: number;
        uniqueText1Count: number;
        uniqueText2Count: number;
        topCommonWords: string[];
    };
    reportPath: string | null;
    reportStatus: string | null;
}

const TextSimilarity: React.FC = () => {
    const [texts, setTexts] = useState<TextDataResponseVO[]>([]);
    const [algorithms, setAlgorithms] = useState<AlgorithmConfigVO[]>([]);
    const [selectedText1, setSelectedText1] = useState<number>();
    const [selectedText2, setSelectedText2] = useState<number>();
    const [selectedAlgorithm, setSelectedAlgorithm] = useState<number>();
    const [loading, setLoading] = useState(false);
    const [result, setResult] = useState<SimilarityResult | null>(null);

    // 获取文本列表
    useEffect(() => {
        const fetchTexts = async () => {
            try {
                const response = await textApi.getTextsByPage({
                    current: 1,
                    pageSize: 100 // 设置一个较大的值以获取更多文本
                });
                if (response.code === 200) {
                    setTexts(response.data.records);
                }
            } catch (error) {
                message.error('获取文本列表失败');
            }
        };

        // 获取算法配置列表
        // 修改获取算法配置列表的函数
        const fetchAlgorithms = async () => {
            try {
                const response = await algorithmApi.getAlgorithmList({
                    current: 1,
                    size: 100
                });

                // 添加空值检查
                if (response.code === 200 && response.data) {
                    setAlgorithms(response.data.records);
                } else {
                    // 如果没有数据，设置为空数组
                    setAlgorithms([]);
                    message.warning('暂无算法配置数据');
                }
            } catch (error) {
                console.error('获取算法配置失败:', error);
                message.error('获取算法配置失败');
                // 发生错误时设置为空数组
                setAlgorithms([]);
            }
        };

        fetchTexts();
        fetchAlgorithms();
    }, []);

    // 计算相似度
    const handleCompute = async () => {
        if (!selectedText1 || !selectedText2 || !selectedAlgorithm) {
            message.warning('请选择两个文本和一个算法配置');
            return;
        }

        // 构造请求参数
        const params: SimilarityRequest = {
            textId1: selectedText1,
            textId2: selectedText2,
            algorithmId: selectedAlgorithm
        };

        setLoading(true);
        try {
            const response = await textApi.computeTextSimilarity(params);
            if (response.code === 200) {
                setResult(response.data);
                message.success('计算完成');
            } else {
                message.error(response.message || '计算失败');
            }
        } catch (error) {
            message.error('计算失败');
            console.error('计算错误:', error);
        } finally {
            setLoading(false);
        }
    };
// 获取雷达图配置
    const getRadarOption = () => {
        if (!result) return {};

        const details = result.analysisDetails;
        return {
            title: {
                text: '文本特征对比'
            },
            radar: {
                indicator: [
                    { name: '文本长度', max: Math.max(details.text1Length, details.text2Length) },
                    { name: '唯一词数', max: Math.max(details.uniqueText1Count, details.uniqueText2Count) },
                    { name: '共同词数', max: details.commonTermsCount },
                    { name: '相似度', max: 1 },
                    { name: '词汇丰富度', max: 1 }
                ]
            },
            series: [{
                type: 'radar',
                data: [
                    {
                        value: [
                            details.text1Length,
                            details.uniqueText1Count,
                            details.commonTermsCount,
                            result.chartData.similarityGauge.score,
                            details.uniqueText1Count / details.text1Length
                        ],
                        name: '文本1',
                        areaStyle: {
                            opacity: 0.3
                        }
                    },
                    {
                        value: [
                            details.text2Length,
                            details.uniqueText2Count,
                            details.commonTermsCount,
                            result.chartData.similarityGauge.score,
                            details.uniqueText2Count / details.text2Length
                        ],
                        name: '文本2',
                        areaStyle: {
                            opacity: 0.3
                        }
                    }
                ]
            }]
        };
    };

    // 获取热力图配置
    const getHeatmapOption = () => {
        if (!result) return {};

        const { labels, text1Frequencies, text2Frequencies } = result.chartData.wordFrequency;
        const data = labels.map((label, index) => [
            index,
            0,
            text1Frequencies[index]
        ]).concat(labels.map((label, index) => [
            index,
            1,
            text2Frequencies[index]
        ]));

        return {
            title: {
                text: '词频热力分布'
            },
            tooltip: {
                position: 'top'
            },
            grid: {
                height: '50%',
                top: '10%'
            },
            xAxis: {
                type: 'category',
                data: labels,
                splitArea: {
                    show: true
                }
            },
            yAxis: {
                type: 'category',
                data: ['文本1', '文本2'],
                splitArea: {
                    show: true
                }
            },
            visualMap: {
                min: 0,
                max: Math.max(...text1Frequencies, ...text2Frequencies),
                calculable: true,
                orient: 'horizontal',
                left: 'center',
                bottom: '15%'
            },
            series: [{
                name: '词频分布',
                type: 'heatmap',
                data: data,
                label: {
                    show: true
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
    };

    // 获取文本组成饼图配置
    const getPieOptions = () => {
        if (!result) return [{}, {}];

        const text1Data = [
            { value: result.analysisDetails.commonTermsCount, name: '共同词汇' },
            { value: result.analysisDetails.uniqueText1Count, name: '独有词汇' }
        ];

        const text2Data = [
            { value: result.analysisDetails.commonTermsCount, name: '共同词汇' },
            { value: result.analysisDetails.uniqueText2Count, name: '独有词汇' }
        ];

        const pieOption = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                bottom: 10
            },
            series: [
                {
                    name: '词汇组成',
                    type: 'pie',
                    radius: '50%',
                    data: [],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        return [
            {
                ...pieOption,
                title: { text: '文本1词汇组成' },
                series: [{ ...pieOption.series[0], data: text1Data }]
            },
            {
                ...pieOption,
                title: { text: '文本2词汇组成' },
                series: [{ ...pieOption.series[0], data: text2Data }]
            }
        ];
    };

    // 改进后的仪表盘配置
    const getEnhancedGaugeOption = () => {
        if (!result) return {};

        const { score, thresholds } = result.chartData.similarityGauge;
        return {
            series: [{
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 1,
                splitNumber: 10,
                itemStyle: {
                    color: score >= thresholds.high ? '#67e0e3' :
                        score >= thresholds.medium ? '#37a2da' :
                            score >= thresholds.low ? '#fd666d' : '#ff0000'
                },
                progress: {
                    show: true,
                    width: 30,
                    roundCap: true,
                    clip: false
                },
                pointer: {
                    show: true,
                    width: 6
                },
                axisLine: {
                    lineStyle: {
                        width: 30,
                        color: [
                            [thresholds.low, '#fd666d'],
                            [thresholds.medium, '#37a2da'],
                            [thresholds.high, '#67e0e3'],
                            [1, '#37a2da']
                        ]
                    }
                },
                axisTick: {
                    distance: -45,
                    splitNumber: 5,
                    lineStyle: {
                        width: 2,
                        color: '#999'
                    }
                },
                splitLine: {
                    distance: -52,
                    length: 14,
                    lineStyle: {
                        width: 3,
                        color: '#999'
                    }
                },
                axisLabel: {
                    distance: -20,
                    color: '#999',
                    fontSize: 12,
                    formatter: function(value: number) {
                        if (value === 1) return '高';
                        if (value === 0) return '低';
                        return value.toString();
                    }
                },
                title: {
                    offsetCenter: [0, '20%'],
                    fontSize: 14
                },
                detail: {
                    valueAnimation: true,
                    width: '60%',
                    lineHeight: 40,
                    borderRadius: 8,
                    offsetCenter: [0, '60%'],
                    fontSize: 40,
                    fontWeight: 'bolder',
                    formatter: function(value: number) {
                        return value.toFixed(2);
                    },
                    color: 'inherit'
                },
                data: [{
                    value: score,
                    name: '相似度得分'
                }]
            }]
        };
    };


    return (
        <div className={styles.container}>
            <Card title="文本相似度分析" className={styles.mainCard}>
                <Space direction="vertical" size="large" style={{ width: '100%' }}>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Select
                                placeholder="选择第一个文本"
                                style={{ width: '100%' }}
                                onChange={setSelectedText1}
                                value={selectedText1}
                                options={texts.map(text => ({
                                    label: `${text.title} (ID: ${text.textId})`,
                                    value: text.textId,
                                }))}
                            />
                        </Col>
                        <Col span={8}>
                            <Select
                                placeholder="选择第二个文本"
                                style={{ width: '100%' }}
                                onChange={setSelectedText2}
                                value={selectedText2}
                                options={texts.map(text => ({
                                    label: `${text.title} (ID: ${text.textId})`,
                                    value: text.textId,
                                }))}
                            />
                        </Col>
                        <Col span={8}>
                            <Select
                                placeholder="选择算法配置"
                                style={{ width: '100%' }}
                                onChange={setSelectedAlgorithm}
                                value={selectedAlgorithm}
                                options={algorithms.map(algo => ({
                                    label: `${algo.name} (ID: ${algo.algorithmId})`,
                                    value: algo.algorithmId,
                                }))}
                            />
                        </Col>
                    </Row>

                    <Button
                        type="primary"
                        onClick={handleCompute}
                        loading={loading}
                        disabled={!selectedText1 || !selectedText2 || !selectedAlgorithm}
                    >
                        计算相似度
                    </Button>
                    {result && (
                        <div className={styles.resultSection}>
                            <Tabs defaultActiveKey="1">
                                <TabPane tab="相似度概览" key="1">
                                    <Row gutter={[16, 16]}>
                                        <Col span={12}>
                                            <Card title="相似度得分">
                                                <ReactECharts option={getEnhancedGaugeOption()} style={{ height: '400px' }} />
                                            </Card>
                                        </Col>
                                        <Col span={12}>
                                            <Card title="文本特征雷达图">
                                                <ReactECharts option={getRadarOption()} style={{ height: '400px' }} />
                                            </Card>
                                        </Col>
                                    </Row>
                                </TabPane>

                                <TabPane tab="词频分析" key="2">
                                    <Row gutter={[16, 16]}>
                                        <Col span={24}>
                                            <Card title="词频热力分布">
                                                <ReactECharts option={getHeatmapOption()} style={{ height: '400px' }} />
                                            </Card>
                                        </Col>
                                    </Row>
                                    <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
                                        <Col span={12}>
                                            <Card title="文本1词汇组成">
                                                <ReactECharts option={getPieOptions()[0]} style={{ height: '300px' }} />
                                            </Card>
                                        </Col>
                                        <Col span={12}>
                                            <Card title="文本2词汇组成">
                                                <ReactECharts option={getPieOptions()[1]} style={{ height: '300px' }} />
                                            </Card>
                                        </Col>
                                    </Row>
                                </TabPane>

                                <TabPane tab="详细分析" key="3">
                                    <Card title="分析详情" className={styles.detailCard}>
                                        {/* 保持原有的分析详情展示不变 */}
                                        <Row gutter={[16, 16]}>
                                            <Col span={8}>
                                                <div className={styles.detailItem}>
                                                    <span>文本1长度：</span>
                                                    <span>{result.analysisDetails.text1Length}</span>
                                                </div>
                                            </Col>
                                            <Col span={8}>
                                                <div className={styles.detailItem}>
                                                    <span>文本2长度：</span>
                                                    <span>{result.analysisDetails.text2Length}</span>
                                                </div>
                                            </Col>
                                            <Col span={8}>
                                                <div className={styles.detailItem}>
                                                    <span>共同词汇数：</span>
                                                    <span>{result.analysisDetails.commonTermsCount}</span>
                                                </div>
                                            </Col>
                                        </Row>

                                        <div className={styles.segments}>
                                            <h4>相似片段:</h4>
                                            <p>{result.similarSegments || '无'}</p>

                                            <h4>差异片段:</h4>
                                            <p>{result.differentSegments || '无'}</p>
                                        </div>
                                    </Card>
                                </TabPane>
                            </Tabs>
                        </div>
                    )}
                </Space>
            </Card>
        </div>
    );
};

export default TextSimilarity;
